<?php
namespace Application\Api\Controller;

class WeiXinSpUser extends Base
{

    public function loginAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'code') || notSetOrEmpty($data, 'userInfo') || notSetOrEmpty($data, 'phoneInfo')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $code = $data['code'];
        $userInfo = $data['userInfo'];
        $phoneInfo = json_decode($data['phoneInfo'], true);
        $iv = $phoneInfo['iv'];
        $encryptedData = $phoneInfo['encryptedData'];
        $serviceWeiXinSpUser = $this->get(SERVICE_WEIXINSPUSER);
        $result = $serviceWeiXinSpUser->getSession($code);
        if(notSetOrEmpty($result, 'session_key') || notSetOrEmpty($result, 'openid')){
            $this->sendFail('TRY', '', __LINE__);
            return false;
        }
        $sessionKey = $result['session_key'];
        $openId = $result['openid'];
        $phoneTemp = $serviceWeiXinSpUser->decryptPhoneInfo($sessionKey, $iv, $encryptedData);
        if(notSetOrEmpty($phoneTemp, 'purePhoneNumber') || !isPhone($phoneTemp['purePhoneNumber'])){
            $this->sendFail('TRY', '', __LINE__);
            return false;
        }
        $phone = $phoneTemp['purePhoneNumber'];
        /*判断用户存在*/
        $serviceUser = $this->get(SERVICE_USER);
        $user = $serviceUser->getUserByPhonePlus($phone);
        if(empty($user)){
            $userId = $serviceUser->weiXinSpAdd($phone, $openId, $userInfo);
        }
        else{
            $userId = $user->id;
        }
        /*token*/
        $send = [
            'token' => $serviceUser->setToken('sp', $userId)
        ];
        $this->sendSuccess($send);
    }

}